{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import torch\n",
    "from torch import nn\n",
    "from torch.utils.data import TensorDataset, DataLoader\n",
    "import torch.nn.functional as F\n",
    "\n",
    "from sklearn.metrics import accuracy_score\n",
    "import matplotlib.pyplot as plt\n",
    "from sklearn import metrics\n",
    "from sklearn.metrics import r2_score \n",
    "\n",
    "from alpaca.ue import MCDUE\n",
    "from alpaca.utils.datasets.builder import build_dataset\n",
    "from alpaca.utils.ue_metrics import ndcg\n",
    "from alpaca.ue.masks import BasicBernoulliMask\n",
    "import alpaca.nn as ann"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Prepare the dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load dataset\n",
    "dataset = build_dataset('kin8nm', val_split=1_000)\n",
    "x_train, y_train = dataset.dataset('train')\n",
    "x_val, y_val = dataset.dataset('val')\n",
    "x_train.shape, y_val.shape\n",
    "train_ds = TensorDataset(torch.FloatTensor(x_train), torch.FloatTensor(y_train))\n",
    "val_ds = TensorDataset(torch.FloatTensor(x_val), torch.FloatTensor(y_val))\n",
    "train_loader = DataLoader(train_ds, batch_size=512)\n",
    "val_loader = DataLoader(val_ds, batch_size=512)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Define the model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "class MLP(nn.Module):\n",
    "    def __init__(self, layer_sizes, activation=F.celu, dropout_rate=0., dropout_mask=None):\n",
    "        super().__init__()\n",
    "        self.layer_sizes = layer_sizes\n",
    "        self.activation = activation\n",
    "        \n",
    "        self.fcs = nn.ModuleList(\n",
    "            [\n",
    "                nn.Sequential(\n",
    "                    *[\n",
    "                        nn.Linear(layer_sizes[i], layer_sizes[i + 1]),\n",
    "                        ann.Dropout(dropout_rate, dropout_mask)\n",
    "                        if i < len(layer_sizes) - 2 and i != 0\n",
    "                        else nn.Sequential(),\n",
    "                    ]\n",
    "                )\n",
    "                for i, layer in enumerate(layer_sizes[:-1])\n",
    "            ]\n",
    "        )\n",
    "        \n",
    "    def forward(self, x, dropout_rate=0, dropout_mask=None):\n",
    "        for layer_num, fc in enumerate(self.fcs):\n",
    "            x = fc(x)\n",
    "            x = self.activation(x)\n",
    "        return x"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Train the model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Train loss on last batch 0.016562456265091896\n",
      "Train loss on last batch 0.01455281674861908\n"
     ]
    }
   ],
   "source": [
    "# Train models\n",
    "layers = (8, 256, 128, 64, 1)\n",
    "models = [MLP(layers), MLP(layers)]\n",
    "\n",
    "def train(model):\n",
    "    criterion = nn.MSELoss()\n",
    "    optimizer = torch.optim.Adam(model.parameters())\n",
    "    model.train()\n",
    "    for epochs in range(10):\n",
    "        for x_batch, y_batch in train_loader: # Train for one epoch\n",
    "            predictions = model(x_batch)\n",
    "            loss = criterion(predictions, y_batch)\n",
    "            optimizer.zero_grad()\n",
    "            loss.backward()\n",
    "            optimizer.step()\n",
    "    print('Train loss on last batch', loss.item())\n",
    "\n",
    "for model in models:\n",
    "    train(model)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Estimate uncertainty"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "x_batch, y_batch = next(iter(val_loader))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Uncertainty estimation with EnsembleMCDUE approach: 100%|██████████| 25/25 [00:00<00:00, 141.83it/s]\n"
     ]
    }
   ],
   "source": [
    "from alpaca.ue import Ensemble\n",
    "# Calculate uncertainty estimation\n",
    "estimator = Ensemble(models, acquisition=\"std\", reduction=\"mean\")\n",
    "predictions, estimations = estimator(x_batch)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Quality score is  0.9192352139904847\n"
     ]
    }
   ],
   "source": [
    "# Calculate NDCG score for the uncertainty\n",
    "errors = np.abs(estimations - y_batch.reshape((-1)).numpy()) \n",
    "score = ndcg(np.array(errors), estimations)\n",
    "print(\"Quality score is \", score)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
